#include "task_base.h"
#include <QString>

namespace application {
namespace task {

SubTaskBase::SubTaskBase(std::shared_ptr<kernel::ILogger> logger)
    : m_logger(logger)
{
}

kernel::task::TaskStage SubTaskBase::execute(TaskContext& ctx)
{
    switch (m_stage) {
    case kernel::task::TaskStage::Init:
        m_stage = init(ctx);
        break;

    case kernel::task::TaskStage::Running:
        m_stage = run(ctx);
        break;

    case kernel::task::TaskStage::Cleanup:
        m_stage = cleanup(ctx);
        m_cleanupDone = true;
        break;

    case kernel::task::TaskStage::Finished:
        // 已完成，无需执行
        m_cleanupDone = true;
        break;

    default:
        logError("Unknown task stage");
        m_stage = kernel::task::TaskStage::Finished;
        break;
    }

    return m_stage;
}

void SubTaskBase::reset()
{
    m_stage = kernel::task::TaskStage::Init;
    m_cleanupDone = false;
}

void SubTaskBase::forceCleanup(TaskContext& ctx)
{
    if (m_cleanupDone) {
        return;
    }

    m_stage = kernel::task::TaskStage::Cleanup;
    auto result = cleanup(ctx);
    m_cleanupDone = true;
    if (result == kernel::task::TaskStage::Finished) {
        m_stage = result;
    } else {
        m_stage = kernel::task::TaskStage::Finished;
    }
}

kernel::task::TaskStage SubTaskBase::finishWithError(
    TaskContext& ctx,
    const std::string& error)
{
    ctx.setError(error);
    logError(error);
    forceCleanup(ctx);
    m_stage = kernel::task::TaskStage::Finished;
    return m_stage;
}

void SubTaskBase::logInfo(const std::string& message)
{
    if (m_logger) {
        m_logger->info(QString::fromStdString(message));
    }
}

void SubTaskBase::logDebug(const std::string& message)
{
    if (m_logger) {
        m_logger->debug(QString::fromStdString(message));
    }
}

void SubTaskBase::logError(const std::string& message)
{
    if (m_logger) {
        m_logger->error(QString::fromStdString(message));
    }
}

void SubTaskBase::logWarning(const std::string& message)
{
    if (m_logger) {
        m_logger->warning(QString::fromStdString(message));
    }
}

} // namespace task
} // namespace application
